package cn.sofwin.orm.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * 数据库工具类
 * @author ZX
 * @version 1.0
 */
public class Dbutils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        //在系统启动时，立即初始化sqlSessionFactory
        String resource = "mybatis-config.xml";
        SqlSession session = null;
        try (InputStream inputStream = Resources.getResourceAsStream(resource)) {
            // 2.从 XML 中构建 SqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 打开会话
     * @return
     */
    public static SqlSession openSession(){
        return sqlSessionFactory.openSession();
    }

    /**
     * 关闭会话
     * @param sqlSession
     */
    public static void closeSession(SqlSession sqlSession){
        sqlSession.close();
    }

}
